package com.digitalchina.lxnsy.activity.old;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessPlan;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.LandVO;
import com.digitalchina.lxnsy.entity.PlanOptsOrgVO;
import com.digitalchina.lxnsy.entity.ProductPlanListVO;
import com.digitalchina.lxnsy.entity.ProductStandardVO;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.AdminXML;
import com.lzy.okhttputils.model.HttpParams;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2018/8/21 15:07
 * 修改备注：
 * ================================================
 */
public class AddStandardProductionActivityV2 extends BaseActivity {


    @Bind(R.id.tv_time_or_type)
    TextView tvTimeOrType;
    @Bind(R.id.tv_time)
    TextView tvTime;
    @Bind(R.id.layout_time)
    RelativeLayout layoutTime;
    @Bind(R.id.tv1)
    TextView tv1;
    @Bind(R.id.et_area)
    EditText etArea;
    @Bind(R.id.layout_area)
    RelativeLayout layoutArea;
    //    @Bind(R.id.tv_company)
//    TextView tvCompany;
//    @Bind(R.id.layout_company)
//    RelativeLayout layoutCompany;
    @Bind(R.id.bt_next)
    Button btNext;
    @Bind(R.id.tv_stage)
    TextView tvStage;
    @Bind(R.id.layout_stage)
    RelativeLayout layoutStage;
    @Bind(R.id.tv_land)
    TextView tvLand;
    @Bind(R.id.layout_land)
    RelativeLayout layoutLand;

    private String seedDate = ""; // 播种时间 2018-08-22 蔬菜时必填
    private String plantSize = ""; // 种植面积
    private String suitOrgId = ""; // 所属单位Id
    private String productStandardId = ""; // 生产标准Id
    private String farmOperationId = ""; // 农事操作阶段ID
    private String planId = ""; // 生产计划ID（修改时，传入）
    private String landId = ""; // 地块ID


    private List<PlanOptsOrgVO> orgList = new ArrayList<>(); // 企业
    private List<LandVO> landList;

    //选择器
    private OptionsPickerView pvLand, pvStage;
    private int mYear, mMonth, mDayOfMonth;//播种时间  年月日


    private ProductPlanListVO vo = null;

    private ProductStandardVO productStandardVO;

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_add_standard_production_v2);
        setTitle("获取作物种植标准");
    }

    @Override
    public void initMember() {

//        //从ERP进入
//        if (AdminXML.getFarmOperation(activity).equals("1")) {
//            layoutLand.setVisibility(View.VISIBLE);
//            getLandList();
//        } else {
//            layoutLand.setVisibility(View.GONE);
//        }


        BusinessPlan.getOpts(this, mHandler);

        if (getIntent().hasExtra("ProductPlanListVO")) {
            // 修改
            vo = (ProductPlanListVO) getIntent().getSerializableExtra("ProductPlanListVO");
            if (vo != null)
                setView();
        } else {
            // 新增
            productStandardVO = (ProductStandardVO) getIntent().getSerializableExtra("ProductStandardVO");

            productStandardId = productStandardVO.getId();

            List<List<ProductStandardVO.PhaseMsgInfosBean.FarmOperationBean>> list = new ArrayList<>();
            for (int i = 0; i < productStandardVO.getPhaseMsgInfos().size(); i++) {
                if (productStandardVO.getPhaseMsgInfos().get(i).getFarmOperation() != null)
                    list.add(productStandardVO.getPhaseMsgInfos().get(i).getFarmOperation());
            }

            // 初始化阶段
            pvStage = new OptionsPickerView.Builder(AddStandardProductionActivityV2.this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3, View v) {


                    String select = productStandardVO.getPhaseMsgInfos().get(options1).getPhaseName() + "-" + productStandardVO.getPhaseMsgInfos().get(options1).getFarmOperation().get(option2).getFarmName();
                    farmOperationId = productStandardVO.getPhaseMsgInfos().get(options1).getFarmOperation().get(option2).getId();
                    tvStage.setText(select);
                }
            })
                    .setSubCalSize(16)//确定取消按钮大小
                    .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                    .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                    .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                    .setContentTextSize(18)//设置滚轮文字大小
                    .setSelectOptions(0)  //设置默认选中项
                    .build();
            pvStage.setPicker(productStandardVO.getPhaseMsgInfos(), list);
        }

    }

    // 修改时 渲染页面
    private void setView() {

        // 计划ID
        planId = vo.getId();
        // 生产标准ID
        productStandardId = vo.getProductStandard().getId();
        // 农事操作阶段ID
        farmOperationId = vo.getFarmOperation().getId();

        tvStage.setText(vo.getPhaseMsgInfo().getPhaseName() + "-" + vo.getFarmOperation().getFarmName());

        List<List<ProductPlanListVO.FarmOperationBean>> list = new ArrayList<>();
        for (int i = 0; i < vo.getProductStandard().getPhaseMsgInfos().size(); i++) {
            if (vo.getProductStandard().getPhaseMsgInfos().get(i).getFarmOperation() != null)
                list.add(vo.getProductStandard().getPhaseMsgInfos().get(i).getFarmOperation());
        }

        // 初始化阶段
        pvStage = new OptionsPickerView.Builder(AddStandardProductionActivityV2.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {


                String select = vo.getProductStandard().getPhaseMsgInfos().get(options1).getPhaseName() + "-" + vo.getProductStandard().getPhaseMsgInfos().get(options1).getFarmOperation().get(option2).getFarmName();
                farmOperationId = vo.getProductStandard().getPhaseMsgInfos().get(options1).getFarmOperation().get(option2).getId();
                tvStage.setText(select);
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvStage.setPicker(vo.getProductStandard().getPhaseMsgInfos(), list);


        // 播种时间
        tvTime.setText(DateUtil.getDate(vo.getSeedDate(), DateStyle.YYYY_MM_DD));

        // 面积
        etArea.setText(vo.getPlantSize() + "");


        if (vo.getLandParcelInfo() != null) {
            landId = vo.getLandParcelInfo().getId();
            tvLand.setText(vo.getLandParcelInfo().getLandParcelName());
        }


    }

    private void setLand(Object obj) {

        landList = FastJsonUtil.getListBean(obj.toString(), "landParcelInfoVOList", LandVO.class);


        pvLand = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                tvLand.setText(landList.get(options1).getPickerViewText());
                landId = landList.get(options1).getLandParcelId();
            }
        })
                .setTitleText("地块")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvLand.setPicker(landList);

    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what) {
                    case MSG.MSG_GET_PLAN_OPTS_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_PLAN_OPTS_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_ADD_PLAN_SUCCESS:
                        showToast("新增成功");
                        ActivityTaskManager.getInstance().closeActivity(StandardProductionActivity.class);
                        ActivityTaskManager.getInstance().closeActivity(SelectProductionDetailActivity.class);
                        ActivityTaskManager.getInstance().closeActivity(SelectProductionActivityV2.class);
                        GotoUtil.gotoActivity(AddStandardProductionActivityV2.this, StandardProductionActivity.class, true);
                        break;
                    case MSG.MSG_ADD_PLAN_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG_S_2:
                        setLand(msg.obj);
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
//        orgList = FastJsonUtil.getListBean(object.toString(), "orgList", PlanOptsOrgVO.class);
//
//
//        pvOrg = new OptionsPickerView.Builder(AddStandardProductionActivityV2.this, new OptionsPickerView.OnOptionsSelectListener() {
//            @Override
//            public void onOptionsSelect(int options1, int option2, int options3, View v) {
//
//                String select = orgList.get(options1).getName();
//                suitOrgId = orgList.get(options1).getId();
//                tvCompany.setText(select);
//            }
//        })
//                .setSubCalSize(16)//确定取消按钮大小
//                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
//                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
//                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
//                .setContentTextSize(18)//设置滚轮文字大小
//                .setSelectOptions(0)  //设置默认选中项
//                .build();
//
//        pvOrg.setPicker(orgList);

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.layout_time, R.id.layout_land, R.id.bt_next, R.id.layout_stage})
    public void onViewClicked(View view) {
        hideKeyboard();
        switch (view.getId()) {
            case R.id.layout_land:
                if (landList == null || landList.size() <= 0)
                    showToast("正在获取地块");
                else
                    pvLand.show();
                break;
            case R.id.layout_time:
                showDatePicker();
                break;
            case R.id.layout_stage:
                pvStage.show();
                break;
            case R.id.bt_next:
                next();
                break;
        }
    }

    // 下一步
    private void next() {

        seedDate = tvTime.getText().toString();
        if (StringUtil.isStrEmpty(seedDate)) {
            showToast("请选择播种时间");
            return;
        }

        plantSize = etArea.getText().toString();
        if (StringUtil.isStrEmpty(plantSize)) {
            showToast("请填写面积");
            return;
        }

//        //从ERP进入
//        if (AdminXML.getFarmOperation(activity).equals("1")) {
//            if (StringUtil.isTextEmpty(tvLand)) {
//                showToast("请选择地块");
//                return;
//            }
//        }


        if (StringUtil.isTextEmpty(tvStage)) {
            showToast("请选择作物阶段");
            return;
        }


        BusinessPlan.addPlan(this, planId, seedDate, plantSize, suitOrgId, productStandardId, farmOperationId, landId, mHandler);
    }


    /**
     * 显示日期选择
     */
    private void showDatePicker() {

        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                String selectDate = year + "-" + (month + 1) + "-" + dayOfMonth;
                tvTime.setText(selectDate);
            }
        }, mYear, mMonth, mDayOfMonth);

//        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() - 1000);
        datePickerDialog.show();
    }

    // 获取地块
    private void getLandList() {
        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));

        OkHttpUtil.post(activity, URL.URL_GET_LAND_LIST, "", params, mHandler,
                MSG_S_2, MSG_F_2);
    }

}
